package cn.ratel.route;

import cn.ratel.exception.RatelException;
import cn.ratel.route.render.Forward;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * author iver
 */
public class ExceptionHolder {
	private static Logger log = LoggerFactory.getLogger(ExceptionHolder.class);
	private static Holder holder = (req, res, e) -> {
		if (e instanceof RatelException) {
			RatelException ex = (RatelException) e;
			if (ex.getCauseType() == RatelException.Cause._404) {
				DefaultRenders.FORWARD.render(req, res, new Forward("/404.html"));
			}
		} else {
			log.error("[EX_HOLDER] uri={} ; params={} ; msg={}", ContextHolder.getUri().get(), ContextHolder.getParameterMap().get(), e.getMessage(), e);
			throw new RuntimeException(e);
		}
	};

	public interface Holder {
		void hold(HttpServletRequest req, HttpServletResponse res, Exception e) throws RuntimeException;
	}

	public static Holder getHolder() {
		return holder;
	}

	public static void setHolder(Holder holder) {
		ExceptionHolder.holder = holder;
	}
}
